package com.yneusoft.manage.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.common.tool.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.yneusoft.common.enums.ResultEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt token拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        ResponseWrapper wrapper ;

        if (!token.equals("token")){
            try {
                JWTUtils.verify(token);
                return true;
            }catch (TokenExpiredException e){
                wrapper = ResponseWrapper.markError(ResultEnum.TOKEN_TIMEOUT);
            }catch (SignatureVerificationException e) {
                wrapper = ResponseWrapper.markError(ResultEnum.TOKEN_SIGN_ERROR);
            }catch (Exception e) {
                wrapper = ResponseWrapper.markError(ResultEnum.TOKEN_ERROR);
                e.printStackTrace();
            }
        }else
            wrapper=ResponseWrapper.markError(ResultEnum.AUTH_HEADER_NULL);
        String json=new ObjectMapper().writeValueAsString(wrapper);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
